// services/api.ts - Axios 实例配置
import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig } from 'axios';

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api/v1';

// 创建 Axios 实例
export const apiClient: AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器 - 自动添加当前连接参数
apiClient.interceptors.request.use(
  (config) => {
    // 从 localStorage 获取当前连接
    const currentConnection = localStorage.getItem('currentConnection');
    
    if (currentConnection && !config.params?.connection) {
      config.params = {
        ...config.params,
        connection: currentConnection,
      };
    }
    
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器 - 统一错误处理
apiClient.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response) {
      // 服务器返回错误状态码
      const { status, data } = error.response;
      
      switch (status) {
        case 404:
          console.error('Resource not found:', data);
          break;
        case 500:
          console.error('Internal server error:', data);
          break;
        case 409:
          console.error('Conflict:', data);
          break;
        default:
          console.error('API Error:', data);
      }
    } else if (error.request) {
      // 请求已发送但未收到响应
      console.error('No response from server');
    } else {
      // 请求配置错误
      console.error('Request setup error:', error.message);
    }
    
    return Promise.reject(error);
  }
);

// 辅助函数 - 带连接参数的请求
export const apiWithConnection = (connection: string) => {
  return {
    get: <T = any>(url: string, config?: AxiosRequestConfig) =>
      apiClient.get<T>(url, { ...config, params: { ...config?.params, connection } }),
    
    post: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) =>
      apiClient.post<T>(url, data, { ...config, params: { ...config?.params, connection } }),
    
    put: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) =>
      apiClient.put<T>(url, data, { ...config, params: { ...config?.params, connection } }),
    
    delete: <T = any>(url: string, config?: AxiosRequestConfig) =>
      apiClient.delete<T>(url, { ...config, params: { ...config?.params, connection } }),
  };
};

export default apiClient;